import 'dart:convert';
import 'dart:io';

import 'package:flutter/material.dart';

/// @date 2020/08/25  16:17
/// @author 程志强
/// @des 网络请求

class HttpClientRoute extends StatefulWidget {
  @override
  _HttpClientRouteState createState() => _HttpClientRouteState();
}

class _HttpClientRouteState extends State<HttpClientRoute> {
  bool _loading = false;
  String _text = "";

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Http请求"),
      ),
      body: ConstrainedBox(
        constraints: BoxConstraints.expand(),
        child: SingleChildScrollView(
          child: Column(
            children: <Widget>[
              RaisedButton(
                child: Text("获取百度首页"),
                onPressed: _loading ? null : loadData,
              ),
              Container(
                  width: MediaQuery.of(context).size.width-50.0,
                  child: Text(_text)
              )
            ],
          ),
        ),
      ),
    );
  }

  loadData() async {
    setState(() {
      _loading = true;
      _text = "正在请求...";
    });

    try {
      // 创建HttpClient
      HttpClient hc = HttpClient();
      // 打开Http连接
      HttpClientRequest request =
          await hc.getUrl(Uri.parse("http://news.sina.com.cn/o/2020-08-25/doc-iivhvpwy2953106.shtml"));
      // 使用iphone的UA
      request.headers.add("user-agent",
          "Mozilla/5.0 (iPhone; CPU iPhone OS 10_3_1 like Mac OS X) AppleWebKit/603.1.30 (KHTML, like Gecko) Version/10.0 Mobile/14E304 Safari/602.1");
      // 等待连接服务器（会将请求信息发送给服务器）
      HttpClientResponse response = await request.close();
      //读取响应内容
      _text = await response.transform(utf8.decoder).join();

      print("响应头信息：${response.headers}");

      // 关闭client
      hc.close();
    } catch (e) {
      _text = "请求失败：$e";
    } finally {
      setState(() {
        _loading = false;
      });
    }
  }
}
